package com.bandit.config;

import com.bandit.pojo.User;
import com.bandit.service.UserService;
import com.bandit.utils.IpUtil;
import com.bandit.utils.RedisUtil;
import com.bandit.utils.ShiroUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("================执行了授权====================");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        // 拿到当前登录的这个对象
        Subject subject = SecurityUtils.getSubject();
        // 拿到User对象
        User currentUser = (User) subject.getPrincipal();
        // 设置当前用户的权限
        String permission = currentUser.getPermission();
        System.out.println(currentUser.getUsername() + "的权限为 " + permission);
        if(ShiroUtils.ADMIN_TAG.equals(permission)){
            for(String perm : ShiroUtils.isAdmin()){
                info.addRole("admin");
                info.addStringPermission(perm);
            }
        }else if(ShiroUtils.NORMAL_TAG.equals(permission)){
            for(String perm : ShiroUtils.isNormal()){
                info.addRole("normal");
                info.addStringPermission(perm);
            }
        }else {
            for(String perm : ShiroUtils.isGuest()){
                info.addRole("guest");
                info.addStringPermission(perm);
            }
        }
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("=====================执行了认证AuthenticationToken===================");

        UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;
        //连接真实的数据库
        User user = userService.getUserByName(userToken.getUsername());
        if(user == null){
            //没有这个人
            return null; //抛出异常 UnknownAccountException
        }

        // 登录成功 将用户信息存入session
        Subject currentSubject = SecurityUtils.getSubject();
        Session session = currentSubject.getSession();
        session.setAttribute("loginUser",user);

        // 密码认证，shiro做
        return new SimpleAuthenticationInfo(user,user.getPassword(),"");
    }
}
